package cn.fl.institution.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.customer.service.ICstNpBscInfoService;
import cn.fl.customer.vo.CstNpBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.vo.PrjCstAccInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.SystemConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 项目基础信息表 控制层 渤海银行
 */
@Controller
@RequestMapping("/institution/bhbank")
public class PrjBscInfoInsBhbankController {

    private static final Logger logger = LoggerFactory.getLogger(PrjBscInfoInsBhbankController.class);

    @Autowired
    private ICstNpBscInfoService cstNpBscInfoService; // 自然人信息

    @Autowired
    private IPrjCstAccInfoService prjCstAccInfoService;//项目客户基础信息表

    /**
     * 保存 项目客户信息
     */
    @RequestMapping(value = "/saveForBhbank.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO saveForBhbank(HttpServletRequest request) throws BaseException {
        BaseLogUtils.newLogger("saveForBhbank.修改项目客户账户信息："+ JSON.toJSONString(request.getParameterMap()) + "，操作人：" + CurrentThreadContext.getCurrentUserName()).info();
        String cstAccInfoId = request.getParameter("cstAccInfoId");//项目客户信息表id
        String insCode = request.getParameter("insCode");//机构code
        String prjId = request.getParameter("prjId");//项目id
        String cstId = request.getParameter("cstId");//客户id
        String cstNm = request.getParameter("cstNm");//客户姓名
        String monthInc = request.getParameter("monthInc");//月收入
        String certNo = request.getParameter("certNo");//身份证号
        String postProvince = request.getParameter("rgnPrCd");//省
        String postCity = request.getParameter("rgnCyCd");//市
        String certValidSDt = request.getParameter("certValidSDt");//身份证有效起始时间
        String certValidEDt = request.getParameter("certValidEDt");//身份证有效结束时间

        DataResultVO dataResultVO = null;
        try {
            if (StringUtils.isEmpty(prjId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目id为空!");
            }
            if (StringUtils.isEmpty(cstId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户id为空!");
            }
            if (StringUtils.isEmpty(cstNm)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户名称为空!");
            }
            if(StringUtils.isEmpty(monthInc)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护月收入!");
            }
            if(StringUtils.isBlank(postProvince)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护居住地-省!");
            }
            if(StringUtils.isBlank(postCity)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护居住地-市!");
            }
            if(StringUtils.isBlank(certValidSDt)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护证件有效起始日期!");
            }
            if(StringUtils.isBlank(certValidEDt)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护证件有效终止日期!");
            }
            if (!certValidEDt.equals(PropertiesCacheUtils.getProperty(SystemConstant.CHECK_DATE_LONG))) {
                Date startDate = DateUtils.formatStringToDate(certValidSDt, "yyyy-MM-dd");
                Date endDate = DateUtils.formatStringToDate(certValidEDt, "yyyy-MM-dd");
                if (DateUtils.equals(startDate, endDate) || DateUtils.after(endDate, startDate)) {
                    return new DataResultVO(BaseConstant.IS_YESNO_NO, "证件有效起始日期 不能大于等于 证件有效终止日期！");
                }
            }

            // 修改自然人居住地,月收入
            CstNpBscInfoVO bscInfoVO = this.cstNpBscInfoService.selectById(Long.valueOf(cstId));
            CstNpBscInfoVO cstNpBscInfoVO = new CstNpBscInfoVO();
            if(null != bscInfoVO) {
                boolean flag = false;
                cstNpBscInfoVO.setId(bscInfoVO.getId());
                Long mrIncMoney = DecimalUtils.convertYuanToFen(Double.valueOf(monthInc)); // 月收入转为分
                Double yrInc = DecimalUtils.mul(mrIncMoney.doubleValue(),12d); // 月收入转换年收入
                if (!Objects.equals(bscInfoVO.getYrInc().doubleValue(), yrInc)) {
                    cstNpBscInfoVO.setYrInc(yrInc.longValue());
                    flag = true;
                }
                if (!Objects.equals(bscInfoVO.getPostProvince(), postProvince) || !Objects.equals(bscInfoVO.getPostCity(), postCity)) {
                    cstNpBscInfoVO.setPostProvince(postProvince);
                    cstNpBscInfoVO.setPostCity(postCity);
                    flag = true;
                }
                if (!Objects.equals(bscInfoVO.getCertValidSDt(), certValidSDt) || !Objects.equals(bscInfoVO.getCertValidEDt(), certValidEDt)) {
                    cstNpBscInfoVO.setCertValidSDt(certValidSDt);
                    cstNpBscInfoVO.setCertValidEDt(certValidEDt);
                    flag = true;
                }
                if (flag) {
                    cstNpBscInfoVO.setMdfTm(new Date());
                    cstNpBscInfoVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                }
                BaseLogUtils.newLogger("saveForBhbank.修改自然人信息cstNpBscInfoVO"+ JSON.toJSONString(cstNpBscInfoVO)).info();
                boolean modify = this.cstNpBscInfoService.modify(cstNpBscInfoVO);
                BaseLogUtils.newLogger("saveForBhbank.修改自然人信息modify=" + modify).info();
            }
            // 修改项目客户信息
            PrjCstAccInfoVO vo = new PrjCstAccInfoVO();
            vo.setPrjId(Long.valueOf(prjId));
            vo.setCstId(Long.valueOf(cstId));
            vo.setInsCode(insCode);
            vo.setCstNm(cstNm);
            vo.setAccNm(cstNm);
            vo.setCertNo(certNo.trim());
            vo.setCertTypCd(DictionaryConstant.CODE_CERT_TYP_CD_0);
            BaseLogUtils.newLogger("saveForBhbank.修改项目客户账户信息,cstAccInfoId:{},condition:{}",cstAccInfoId, JSONObject.toJSONString(vo)).info();
            if (StringUtils.isNotEmpty(cstAccInfoId)) {
                vo.setId(Long.valueOf(cstAccInfoId));
                boolean flag = prjCstAccInfoService.modify(vo);
                BaseLogUtils.newLogger("saveForBhbank.修改项目客户账户信息,flag:"+ flag).info();
                if (flag == false) {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo("修改项目客户账户信息失败");
                }
            } else {
                Long add = prjCstAccInfoService.add(vo);
                BaseLogUtils.newLogger("saveForBhbank.新增项目客户账户信息,id:"+ add).info();
            }
        } catch (BaseException ex) {
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("saveForBhbank.保存项目客户账户信息及校验,prjId:" + prjId + ".ERROR:" + ex.getMessage()).info();
        } catch (Exception e) {
            BaseLogUtils.newLogger("saveForBhbank.保存失败，系统异常" + e).info();
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "保存失败，系统异常");
        }
        BaseLogUtils.newLogger("saveForBhbank.保存项目客户账户信息及校验返回dataResultVO=" +
                JSON.toJSONString(dataResultVO)).info();
        return dataResultVO;
    }
}
